<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//
define('SYS_RT_DIR_CACHE', CONFIG_PATH . CONFIG_DIR_CACHE);
//
function func_cache_get_settings() {
	$file =  SYS_RT_DIR_CACHE . 'cache_settings.php';
	if( file_exists($file) ) {
		include_once($file);
	} else {
		$cachedata = 'global $SETTINGS' . ";\n\n" . '$SETTINGS = ' . func_cache_getcachearray('settings') . ";\n\n";
		func_cache_writetocache('settings', '', $cachedata);
		
		include_once($file);
	}
}

function func_cache_getcachearray($name, $script = '') {
	global $adb;
	
	if( $name == 'settings' ) {
		include_once(CONFIG_PATH . CONFIG_DIR_CLASSES . 'setting.class.php');
		$settingObj = new CoreSettingBase();
		$SETTINGS = $settingObj->getSettings();
		
		$cachearray = func_cache_arrayeval($SETTINGS);
	}
	
	return $cachearray;
}

function func_cache_writetocache($script, $cachenames, $cachedata = '', $prefix = 'cache_') {
	if( is_array($cachenames) && !$cachedata ) {
		foreach($cachenames as $name) {
			$cachedata .= func_cache_getcachearray($name, $script);
		}
	}
	
	$dir = SYS_RT_DIR_CACHE;
	if( !is_dir($dir) ) {
		@mkdir($dir, 0777);
	}
	if( $fp = @fopen("$dir$prefix$script.php", 'wb') ) {
		$content = "<?php\n//Cache file, DO NOT modify me!" 
				. "\n//Created: " . date("M j, Y, G:i") 
				. "\n//Identify: " . md5($prefix . $script . '.php'. $cachedata) . "\n\n" 
				. "$cachedata?>";
		fwrite($fp, $content);
		fclose($fp);
	} else {
		exit('Can not write to cache files, please check directory.');
	}
}

function func_cache_arrayeval($data_array, $level = 0) {
	if( !is_array($data_array) ) {
		return "'" . $data_array . "'";
	}
	if( is_array($data_array) && function_exists('var_export') ) {
		return var_export($data_array, true);
	}
	
	$space = '';
	for($i=0; $i<=$level; $i++) {
		$space .= "\t";
	}
	$evaluate = "Array\n$space(\n";
	$comma = $space;
	if( is_array($data_array) ) {
		foreach($data_array as $key => $value) {
			$key = is_string($key) ? '\'' . addcslashes($key, '\'\\') . '\'' : $key;
			$value = !is_array($value) && (!preg_match("/^\-?[1-9]\d*$/", $value) || strlen($value) > 12) ? '\''.addcslashes($value, '\'\\').'\'' : $value;
			if( is_array($value) ) {
				$evaluate .= "$comma$key => " . func_cache_arrayeval($value, $level + 1);
			} else {
				$evaluate .= "$comma$key => $value";
			}
			$comma = ",\n$space";
		}
	}
	$evaluate .= "\n$space)";
	
	return $evaluate;
}
//
?>